var rootPath = '';//kk.getRootPath();

/* customerDom */
var customerDom = '\
<div class="box box-skin-inner sub-content">\
	<div class="box-header with-border">\
		<span class="box-title"></span>\
		<div class="box-tools pull-right">\
			<button type="button" class="btn btn-box-tool btnCancel" data-widget="remove"><i class="fa fa-times"></i></button>\
		</div>\
	</div>\
	<div class="box-body">\
		<div class="row">\
		<form class="form-horizontal" id="customerForm">\
			<div class="col-sm-7">\
				<div class="form-group">\
					<label for="myFile" class="col-sm-2 control-label">头像</label>\
					<div class="col-sm-10">\
						<input type="file" id="myFile" name="file" />\
						<input type="hidden" id="avatar" name="avatar" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="real_nameame" class="col-sm-2 control-label">姓名<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="real_name" name="real_name" placeholder="姓名" />\
					</div>\
				</div><!--\
				<div class="form-group">\
					<label for="username" class="col-sm-2 control-label">用户名<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="username" name="username" placeholder="用户名" />\
					</div>\
				</div>-->\
				<div class="form-group">\
					<label for="tel" class="col-sm-2 control-label">电话<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="tel" name="tel" placeholder="电话" />\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="open_id" class="col-sm-2 control-label">OPENID</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="open_id" name="open_id" placeholder="OPENID" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="fam_role" class="col-sm-2 control-label">家庭角色</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="fam_role" name="fam_role" placeholder="家庭角色">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="cust_role" class="col-sm-2 control-label">用户角色</label>\
					<div class="col-sm-10">\
						<div id="cust_role">\
							<input type="radio" name="cust_role" value="1" data-label="普通用户" checked />\
							<input type="radio" name="cust_role" value="2" data-label="录入员" />\
						</div>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="sex" class="col-sm-2 control-label">性别</label>\
					<div class="col-sm-10">\
						<div id="sex">\
							<input type="radio" name="sex" value="1" data-label="\<i class=\'fa fa-mars\'\>\<\/i\> 男" checked />\
							<input type="radio" name="sex" value="2" data-label="\<i class=\'fa fa-venus\'\>\<\/i\> 女" />\
							<input type="radio" name="sex" value="3" data-label="\<i class=\'fa fa-genderless\'\>\<\/i\> 保密" />\
						</div>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="birthday" class="col-sm-2 control-label">出生日期</label>\
					<div class="col-sm-10">\
						<div class="input-group">\
							<input type="text" class="form-control" id="birthday" name="birthday" placeholder="出生日期" />\
							<div class="input-group-addon"><i class="fa fa-calendar"></i></div>\
						</div>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="email" class="col-sm-2 control-label">邮箱</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="email" name="email" placeholder="邮箱" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="address" class="col-sm-2 control-label">地址</label>\
					<div class="col-sm-10">\
						<textarea class="form-control" rows="6" id="address" name="address" placeholder="地址"></textarea>\
					</div>\
				</div><!--\
				<div class="form-group">\
					<label for="cardExpiryTime" class="col-sm-2 control-label">VIP有效期</label>\
					<div class="col-sm-10">\
						<div class="input-group">\
							<input type="text" class="form-control" id="cardExpiryTime" name="cardExpiryTime" placeholder="VIP有效期" />\
							<div class="input-group-addon"><i class="fa fa-calendar"></i></div>\
						</div>\
					</div>\
				</div>-->\
				<div class="form-group">\
					<label for="sortOrder" class="col-sm-2 control-label">排序</label>\
					<div class="col-sm-10">\
						<input type="number" class="form-control" id="sortOrder" name="sortOrder" placeholder="排序" value="0" min="0" max="1000" />\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="updateTime" class="col-sm-2 control-label">更新时间</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="updateTime" name="updateTime" placeholder="更新时间" />\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="addTime" class="col-sm-2 control-label">添加时间</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="addTime" name="addTime" placeholder="添加时间" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="description" class="col-sm-2 control-label">描述</label>\
					<div class="col-sm-10">\
						<textarea class="form-control" rows="6" name="description" placeholder="描述"></textarea>\
					</div>\
				</div>\
			</div>\
			<div class="col-sm-5">\
				<div class="foo">\
					<p class="text-muted">1. 图片的尺寸为450*450</p>\
					<p class="text-muted">2. 姓名和电话必填</p>\
					<p class="text-muted">3. 性别、出生日期、邮箱可不设置</p>\
					<p class="text-muted">4. 排序越小，实际显示越靠前</p>\
					<p class="text-muted">5. VIP有效期慎重设置</p>\
				</div>\
			</div>\
			<div>\
				<input type="hidden" name="id" />\
			</div>\
		</form>\
		</div>\
	</div>\
	<div class="box-footer text-center">\
	    <button type="button" class="btn btn-info btn-flat btnOK">确定</button>\
	    <button type="button" class="btn btn-default btn-flat btnCancel">取消</button>\
	</div>\
</div>\
';

/* CRUD 1: Create, 2: Read, 3: Update, 4: Delete */
var CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4;
function CRUDCustomerFunc(operCode, id, index) {
	var canOpen = false;
	var url;
	var obj;
	
	if (operCode == CREATE) {
		canOpen = true;
	} else if (operCode == READ || operCode == UPDATE) {
		url = rootPath + '/Customer/Customer/find?id=' + id;
		obj = kk.getObj(url);
		if (obj != null) {
			canOpen = true;
		}
	} else if (operCode == DELETE) {
		url = rootPath + '/Customer/Customer/delete?id=' + id;
		kk.deleteObj(url, '#table');
	} else {
		return false;
	}
	
	if (!canOpen) {
		return false;
	}
	
	$('.main-content').hide();
	$('.main-content').after(customerDom);
	
	var xqu = xqupload('#myFile', {
		uploadUrl			: rootPath + '/Asset/Upload/upload?savePath=customer_avatar',
        recvObj				: '#avatar'
    });
	
	$('#birthday').datetimepicker({
	    format: 'yyyy-mm-dd',
	    minView: 'month',
	    autoclose: true,
	    todayBtn: true
	});
//		$('#cardExpiryTime').datetimepicker({
//		    format: 'yyyy-mm-dd hh:ii:ss',
//		    autoclose: true,
//		    todayBtn: true
//		});
	
	if (operCode == CREATE) {
		$('.box-title').empty().append('添加');

    	xupload('#myFile', {
    		height: 220,
    		changeHandler: function($this) {
    			$('#avatar').val('');
    			
    			lrz($('#myFile')[0].files[0], {width: 450, quality: 0.8}).then(function (rst) {
    	            // 处理成功会执行
    	            console.log(rst);
    	            $this.setFile(rst.base64);
        			
        			var filename = $('#myFile').val();
        		    var fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';			// fileExt
        		    var key = kk.getProjectName() + '/customers/' + new Date().format("yyMMddhhmmssS") + kk.mathRand(1) + '.' + fileExt;
        			xqu.upload(rst.formData, key);
    	        }).catch(function (err) {
    	            // 处理失败会执行
    	        }).always(function () {
    	            // 不管是成功失败，都会执行
    	        });
    		}
    	});
    	$('#birthday').val(kk.timeFormat('yyyy-MM-dd'));
//        	$('#cardExpiryTime').val(kk.timeFormat('yyyy-MM-dd HH:mm:ss'));

		$('.rm-or-hide').remove();
	} else if (operCode == READ) {
		$('.box-title').empty().append('查看');
		$('.btnOK').hide();
		$('.btnCancel').text('关闭');

		$('#customerForm').setForm(obj);
    	xupload('#myFile', {
    		height: 220,
    		defaultFile: rootPath + '/' + obj.avatar,
    		isDisabled: true
    	});
		$('#birthday').val(kk.timeFormat('yyyy-MM-dd', obj.birthday));
//        	$('#cardExpiryTime').val(kk.timeFormat('yyyy-MM-dd HH:mm:ss', obj.cardExpiryTime));
		$('#addTime').val(kk.timeFormat('yyyy-MM-dd HH:mm:ss', obj.addTime));
		$('#updateTime').val(kk.timeFormat('yyyy-MM-dd HH:mm:ss', obj.updateTime));

		$('#customerForm').find(':input').attr("disabled", "disabled");		// 习惯性地处理
	} else if (operCode == UPDATE) {
		$('.box-title').empty().append('编辑');
		
		$('#customerForm').setForm(obj);
    	xupload('#myFile', {
    		height: 220,
    		defaultFile: rootPath + '/' + obj.avatar,
    		changeHandler: function($this) {
    			$('#avatar').val('');
    			
    			lrz($('#myFile')[0].files[0], {width: 450, quality: 0.8}).then(function (rst) {
    	            // 处理成功会执行
    	            console.log(rst);
    	            $this.setFile(rst.base64);
        			
        			var filename = $('#myFile').val();
        		    var fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';			// fileExt
        		    var key = kk.getProjectName() + '/customers/' + new Date().format("yyMMddhhmmssS") + kk.mathRand(1) + '.' + fileExt;
        			xqu.upload(rst.formData, key);
    	        }).catch(function (err) {
    	            // 处理失败会执行
    	        }).always(function () {
    	            // 不管是成功失败，都会执行
    	        });
    		}
    	});
		$('#birthday').val(kk.timeFormat('yyyy-MM-dd', obj.birthday));
//        	$('#cardExpiryTime').val(kk.timeFormat('yyyy-MM-dd HH:mm:ss', obj.cardExpiryTime));

		$('.rm-or-hide').hide();
	}
	
	xrs("input:radio[name='sex']", {
		xRsLabelClass: 'xrs-label-info',
	});
	xrs("input:radio[name='cust_role']", {
		xRsLabelClass: 'xrs-label-info',
		iconEnable: true,
	});

	var validator = $("#customerForm").validate({
		onfocusout: function(element) {
			$(element).valid();
		},
        rules: {
			real_name: "required",
//				username: "required",
			tel: "required"
        },
        messages: {
        	real_name: "请输入姓名",
//				username: "请输入用户名",
			tel: "请输入电话"
        }
    });
	
	$('.btnOK').off('click').on('click', function() {
 		if (validator.form() && doCU(operCode, id, index)) {
			$('.sub-content').remove();
			$('.main-content').show();
 		}
	});
	
	$('.btnCancel').off('click').on('click', function() {
		xqu.abort();
		
		$('.sub-content').remove();
		$('.main-content').show();
	});
}

/* Create & Update */
function doCU(operCode, id, index) {
    var url;
    var method;
	var result;

	// $('#birthday').val(new Date($('#birthday').val()).getTime());
//	$('#cardExpiryTime').val(new Date($('#cardExpiryTime').val()).getTime());
	var jsonStr = JSON.stringify($('#customerForm').serializeObject());
	
	if (operCode == CREATE) {
	 	url = rootPath + '/Customer/Customer/save';
		method = "POST";

		result = kk.doStrAjax(url, method, jsonStr);
	    if (result.code == 0) {
	    	$('#table').bootstrapTable('insertRow', {
				index: 0,
				row: result.obj
			});
	    	
	    	return true;
		}
	} else if (operCode == UPDATE) {
	 	url = rootPath + '/Customer/Customer/update?id=' + id;
		method = "PUT";

		result = kk.doStrAjax(url, method, jsonStr);
	    if (result.code == 0) {
	    	$('#table').bootstrapTable('updateRow', {
	    		index: index,
				row: result.obj
	    	});
	    	
	    	return true;
		}
	}
	
	return false;
}


/************ audit ************/
function auditCustomerFunc(id, index) {
	var url = rootPath + '/Customer/Customer/audit?id=' + id + '&status=';
	
	xpopup.confirm({
    	title: '审核',
        msg: '审核通过？',
        draggable: true,
        buttons: [{
            text: '通过',
            'class': 'btn btn-success',
            handler: function ($this) {
                var xloading = xpopup.loading();
                
    			$.ajax({
    				type: 'PUT',
    				url : url + '1',
    				dataType: 'json',
    				async : false,
    				success: function(data) {
    		        	xloading.destroy();

    					if (data.code == 0) {
    				   		xpopup.notify({
    				           	style: 'mini',
    				           	type: 'success',
//    				           	title: '操作成功',
    		   	                msg: data.msg,
    							delay: 1000,
    							position: 'center',
    						});

    	                	$('#table').bootstrapTable('updateRow', {
    	        	    		index: index,
    	        				row: data.obj
    	        	    	});
    					} else {
            				kk.extOnLoadSuccess(data);
    					}
    				},
    				error: kk.extError
    			});
    			
        		$this.destroy();
            }
        }, {
            text: '不通过',
            'class': 'btn btn-danger',
            handler: function ($this) {
                var xloading = xpopup.loading();
                
    			$.ajax({
    				type: 'PUT',
    				url : url + '2',
    				dataType: 'json',
    				async : false,
    				success: function(data) {
    		        	xloading.destroy();

    					if (data.code == 0) {
    				   		xpopup.notify({
    				           	style: 'mini',
    				           	type: 'success',
//    				           	title: '操作成功',
    		   	                msg: data.msg,
    							delay: 1000,
    							position: 'center',
    						});

    	                	$('#table').bootstrapTable('updateRow', {
    	        	    		index: index,
    	        				row: data.obj
    	        	    	});
    					} else {
            				kk.extOnLoadSuccess(data);
    					}
    				},
    				error: kk.extError
    			});
    			
        		$this.destroy();
            }
        }, {
            text: '取消',
            'class': 'btn btn-default',
            handler: function ($this) {
        		$this.destroy();
            }
        }]
    });
}


/************ forbidden ************/
function forbiddenCustomerFunc(id, index) {
	var url = rootPath + '/Customer/Customer/audit?id=' + id + '&status=';
	
	xpopup.confirm({
    	title: '禁用',
        msg: '禁用？',
        buttons: [{
            text: '禁用',
            'class': 'btn btn-danger',
            handler: function ($this) {
                var xloading = xpopup.loading();
                
    			$.ajax({
    				type: 'PUT',
    				url : url + '-2',
    				dataType: 'json',
    				async : false,
    				success: function(data) {
    		        	xloading.destroy();

    					if (data.code == 0) {
    				   		xpopup.notify({
    				           	style: 'mini',
    				           	type: 'success',
//    				           	title: '操作成功',
    		   	                msg: data.msg,
    							delay: 1000,
    							position: 'center',
    						});

    	                	$('#table').bootstrapTable('updateRow', {
    	        	    		index: index,
    	        				row: data.obj
    	        	    	});
    					} else {
            				kk.extOnLoadSuccess(data);
    					}
    				},
    				error: kk.extError
    			});
    			
        		$this.destroy();
            }
        }, {
            text: '取消',
            'class': 'btn btn-default',
            handler: function ($this) {
        		$this.destroy();
            }
        }]
    });
}


/************ 会员卡绑定 ************/
var cardBindForm = '\
		<label for="card_no" class="col-sm-2 control-label">会员卡号</label>\
		<div class="col-sm-10">\
			<input type="text" class="form-control" id="card_no" name="card_no" placeholder="会员卡号">\
		</div>\
	';

function cardBind(id, cardNo, index) {
	xpopup.window({
	    width: 600,
		title: '会员卡管理',
	    content: cardBindForm,
        buttons: [{
        	id:	'btnOk',
            text: '确定',
            'class': 'btn btn-info',
            handler: function ($this) {
            	var cardNo = $("#card_no").val() != '' ? $("#card_no").val() : 'unbind';
	    		var url = rootPath + '/Customer/Customer/bindCard?id=' + id + '&cardNo=' + cardNo;
	    		result = kk.doStrAjax(url, "PUT", null);
	    	   	
	    	    if (result.code == 0) {
	    	    	$('#table').bootstrapTable('updateRow', {
	    	    		index: index,
	    				row: result.obj
	    	    	});

            		$this.destroy();
	    		}
            }
        }, {
        	id:	'btnCancel',
            text: '取消',
            'class': 'btn btn-default',
            handler: function ($this) {
        		$this.destroy();
            }
        }],
        afterShow: function ($this) {
        	if (cardNo != 'null') {
        		$('#card_no').val(cardNo);
        	}
        }
	});
}